
<template>
	<div class="page">
    <header>
      <div class="logo"> Torrent Manager <a-icon type="link" title="注销" @click="toWeb" class="link-btn"/></div>
      <a-icon type="poweroff" title="注销" @click="logout" class="logout-btn"/>
    </header>
    <div class="main">
      <!-- <a-button type="primary" block @click="addShow = true">
        检查
      </a-button> -->
      <a-result v-if="!finded" status="warning" title="当前页面未发现种子" sub-title="请在种子详情页打开该插件">
      </a-result>
      <p v-if="finded" class="link-title">
        <img v-if="torrent.favIconUrl" :src="`chrome://favicon/${torrent.favIconUrl}`"/>
        <a-icon v-else type="check-circle" />
        {{ torrent.title }}
      </p>
      <a-card v-for="(link, index) in torrent.links" :key="index" :title="link.title" class="link-card"
        :headStyle="{ padding: '0 12px', fontSize: '14px', fontWeight: 'normal' }"
        :bodyStyle="{ padding: '12px', fontSize: '12px' }"
      >
        <a slot="extra" href="#" @click="toAdd(link)">选择</a>
        <span>{{ link.address }}</span>
      </a-card>
    </div>
    <a-drawer
      title="推送下载"
      width="100%"
      placement="right"
      :closable="true"
      :visible="addShow"
      @close="addClose"
    >
      <AddTorrent ref="addTorrent" :siteOptions="siteOptions" :categoryOptions="categoryOptions" :clientOptions="clientOptions" :libraryOptions="libraryOptions" :success="addSuccess"/>
    </a-drawer>
    <a-drawer
      title=""
      width="100%"
      placement="left"
      :closable="false"
      :visible="successShow"
    >
      <a-result
        status="success"
        title="保存成功"
        sub-title="详细信息请前往 Torrent Manager 查看"
      >
        <template #extra>
          <a-button key="console" type="primary" @click="toWeb">
            Torrent Manger
          </a-button>
          <a-button key="buy" @click="successShow = false">
            知道了
          </a-button>
        </template>
      </a-result>
    </a-drawer>
	</div>
</template>

<script>
import BaseApi from '../../api/api.js'
import AddTorrent from './Add.vue'
import store from '../../store'
export default {
  name: 'Torrent',
  components: {
    AddTorrent
  },
  data() {
    return {
      finded: false,
      siteOptions: [],
      categoryOptions: [],
      clientOptions: [],
      libraryOptions: [],
      addShow: false,
      successShow: false,
      torrent: {
        favIconUrl: '',
        title: '',
        title0: '',
        category: '',
        links: []
      },
      addInfo: {
      }
    }
  },
  async mounted() {
    //
    await this.loadOptions()
    // 监听页面查找结果
    chrome.runtime.onMessage.addListener((request, sender, response) => {
      if (request && request.type === 'TORRENT-INFO') {
        this.torrent.title = request.title
        this.torrent.title0 = request.title0
        this.torrent.category = request.category
        this.torrent.links = request.torrentLinks
        this.finded = this.torrent.links.length > 0
        if (this.torrent.links.length === 1) {
          this.toAdd(this.torrent.links[0])
        }
      }
      // response('hi!')
      return true; // 这是重点，没有return true，上面返回的是undefined而不是"hi!"
    });
    // 当前页面查找种子
    this.findTorrent()
  },
  created() {
  },
  methods: {
    async loadOptions() {
      // 站点
      // const siteOptionsLS = localStorage.getItem('siteOptions')
      // if (siteOptionsLS) {
      //   this.siteOptions = JSON.parse(siteOptionsLS)
      // }
      if (!this.siteOptions || this.siteOptions.length === 0) {
        const response = await BaseApi.siteOptions()
        this.siteOptions = response.data.data
        // localStorage.setItem('siteOptions', JSON.stringify(this.siteOptions))
      }
      // 分类
      // const categoryOptionsLS = localStorage.getItem('categoryOptions')
      // if (categoryOptionsLS) {
      //   this.categoryOptions = JSON.parse(categoryOptionsLS)
      // }
      if (!this.categoryOptions || this.categoryOptions.length === 0) {
        const response = await BaseApi.categoryOptions()
        this.categoryOptions = response.data.data
        // localStorage.setItem('categoryOptions', JSON.stringify(this.categoryOptions))
      }
      // 下载器
      // const clientOptionsLS = localStorage.getItem('clientOptions')
      // if (clientOptionsLS) {
      //   this.clientOptions = JSON.parse(clientOptionsLS)
      // }
      if (!this.clientOptions || this.clientOptions.length === 0) {
        const response = await BaseApi.clientOptions()
        this.clientOptions = response.data.data
        // localStorage.setItem('clientOptions', JSON.stringify(this.clientOptions))
      }

      // 媒体库
      if (!this.libraryOptions || this.libraryOptions.length === 0) {
        const response = await BaseApi.libraryOptions()
        this.libraryOptions = response.data.data
        // localStorage.setItem('clientOptions', JSON.stringify(this.clientOptions))
      }
    },
    getMainDom() {
      return this.$refs.main
    },
    addClose() {
      this.addShow = false
    },
    findTorrent() {
      chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        if (tabs.length > 0) {
          // this.torrent.favIconUrl = tabs[0].favIconUrl
          chrome.tabs.executeScript(tabs[0].id, {
            file: 'js/content-script.js'
          })
        }
      })
    },
    toAdd(link) {
      this.addShow = true
      this.$nextTick(() => {
        this.$refs.addTorrent.setInfo({
          title: this.torrent.title,
          title0: this.torrent.title0,
          address: link.address,
          category: this.torrent.category
        })
      })
    },
    addSuccess() {
      this.addShow = false
      this.successShow = true
    },
    toWeb() {
      const serverUrl = store.state.serverUrl
      chrome.cookies.set({ name: 'TM-Token', url: serverUrl, value: store.state.token }, () => {
        chrome.tabs.query({ url: serverUrl + '/*', currentWindow: true }, tabs => {
          if (tabs.length > 0) {
            chrome.tabs.reload(tabs[0].id, {}, () => {
              chrome.tabs.update(tabs[0].id,
              {
                active: true
              })
            })
          } else {
            chrome.tabs.create({
              url: serverUrl
            })
          }
        })
      })
    },
    logout() {
      chrome.cookies.remove({ name: 'TM-Token', url: store.state.serverUrl })
      store.dispatch('setToken', '')
      localStorage.removeItem('siteOptions')
      localStorage.removeItem('categoryOptions')
      localStorage.removeItem('clientOptions')
      this.$router.replace({
        path: "/login"
      });
    }
  }
}
</script>
<style scoped>
  .page {
    height: 100%;
  }
  header {
    height: 42px;
    padding: 0 20px;
    line-height: 42px;
    background: #1c1b1b;
  }
  .logo {
    color: #f15a2c;
    font-weight: bolder;
    font-size: 20px;
  }
  .link-btn {
    font-size: 14px;
  }
  .logout-btn {
    color: white;
    position: absolute;
    top: 14px;
    right: 14px;
    font-size: 16px;
  }
  .main {
    position: relative;
    height: calc(100% - 42px);
    padding-top: 10px;
    overflow-y: scroll;
  }
  .link-title {
    margin: 0 10px 10px;
    padding: 8px;
    background-color: #BCCAD6;
    font-weight: 600;
  }
  .link-card {
    margin: 10px 10px;
  }
  .ant-card-body>span {
    overflow-wrap: break-word;
  }
</style>
